package shop.ynubeggar.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import shop.ynubeggar.constant.RedisCacheKey;
import shop.ynubeggar.service.VerifyService;
import shop.ynubeggar.utils.CommonUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Api(tags = "验证")
@RestController
@RequestMapping("/api/user/v1")
public class NotifyController {


    @Resource
    VerifyService verifyService;

    @ApiOperation(value = "获取",notes = "获取图形验证码")
    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String captchaKey = produceCaptchaKey(request);
        BufferedImage image = verifyService.createVerification(captchaKey);
        ServletOutputStream outputStream;
//      已使用全局异常处理下面的输出流
        outputStream = response.getOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        outputStream.flush();
        outputStream.close();
    }

    @ApiOperation(value = "验证", notes = "验证图片验证码")
    @PostMapping("/confirmCaptcha")
    public void confirmCaptcha(@RequestParam(value = "captchaValue") String captchaValue,
                               HttpServletRequest request) {
        String captchaKey = produceCaptchaKey(request);
        verifyService.verifyCode(captchaKey, captchaValue);
    }

    /**
     * 获取验证码缓存的key
     * @param request
     * @return
     */
    public static String produceCaptchaKey(HttpServletRequest request) {
        String ip = request.getRemoteAddr();
        String userAgent = request.getHeader("User-Agent");
        return String.format(RedisCacheKey.CHECK_CODE_KEY, CommonUtils.MD5(ip + userAgent));
    }

}
